import React, { Component, Suspense } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Button,
  Input,
  Modal,
  message,
  Form,
  Select,
  Checkbox,
  Tooltip,
  Table,
  Pagination,
  Upload,
  Icon,
  Radio,
  Spin,
  TreeSelect,
  Divider,
  notification,
} from 'antd';
import axios from 'axios';
import qs from 'qs';
import download from '@/utils/download';
import PageLoading from '@/components/PageLoading';
import MarkdownRenderer from '@/components/common/MarkdownRenderer';
import styles from './index.less';
import RelatedModal from '@/pages/KnowledgeManagement/Overview/qaList/relatedModal';
import {
  exportByQaIds,
  exportByQaIdsCheck,
  exportQA,
  importQACheck,
  knowledgeListQa,
  postBatchSync,
  getBatchSyncCheck,
} from '@/services/knowledgemanagement';
import tableDataCheck from '@/utils/isBackPrevPage';
import UserSession from '@/UserSession';
import moment from 'moment';
const EditingKnowledge = React.lazy(() => import('../EditingKnowledge/editingKnowledge'));
import ReferenceTemplate from '../leftTree/referenceTemplate';
import { MoreOption } from '@/utils/CommonComponent';

const { Option } = Select;
const { confirm } = Modal;
const { Search } = Input;
const RadioGroup = Radio.Group;
const { TreeNode } = TreeSelect;
let checkListInterval = null;
let checkInterval = null;

@connect(({ qaList, loading }) => ({
  qaList,
  loading: loading.effects['qaList/fetchListBySearch'],
}))
class QaList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      limit: 10,
      categoryId: '/',
      visible: false,
      qaIdList: [],
      close: false,
      categoryName: '',
      loading: false,
      tableLoading: true,
      mergeVisible: false,
      key: '',
      qaLimit: 6,
      qaPage: 1,
      qaRes: [],
      qaTotal: 0,
      qaLoading: true,
      res: [],
      total: 0,
      mergeId: '',
      classVisible: false,
      classLoading: true,
      classTreeData: [],
      classId: '',
      qaKey: '',
      searchObj: {},
      nodePath: '',
      code: 1,
      queryType: 1,
      sortType: 1,
      disabled: 'All',
      qaType: 'All',
      selectedRowKeys: [],
      fileList: [],
      uploading: false,
      isNoAnswer: props.noAnswer !== undefined ? props.noAnswer : false,
      isShard: props.isShared ? props.isShared : false,
      categoryParentId: '0',
      categoryParentPath: '/0',
      defaultExpandedKey: '',
      exportLoading: false,
      exportTipList: [],
      isNoneAnswer: false,
      moveLoading: false,
      enableLoading: false,
      resynchronizationStatus: null, // 重新同步状态
      addMenuList: [
        {
          key: 'add',
          name: formatMessage({ id: 'knowledgeManagement.qaList.add' }),
        },
        {
          key: 'import',
          name: formatMessage({ id: 'knowledgeManagement.qaList.import' }),
        },
      ],

      batchMenuList: [
        {
          key: 'start',
          name: formatMessage({ id: 'knowledgeManagement.qaList.enable' }),
        },
        {
          key: 'stop',
          name: formatMessage({ id: 'knowledgeManagement.qaList.disable' }),
        },
        {
          key: 'export',
          name: formatMessage({ id: 'knowledgeManagement.qaList.export' }),
        },
        {
          key: 'move',
          name: formatMessage({ id: 'knowledgeManagement.qaList.moveCategory' }),
        },
        {
          key: 'delete',
          name: formatMessage({ id: 'knowledgeManagement.qaList.delete' }),
        },
        {
          key: 'sync',
          name: formatMessage({ id: 'knowledgeManagement.qaList.resync' }),
        },
      ],
    };
    this.sysColumns = [
      {
        key: 'basicQuestion',
        align: 'left',
        title: formatMessage({ id: 'knowledgeManagement.qaList.standardQuestion' }),
        dataIndex: 'basicQuestion',
        width: 200,
        render: (text, row) => {
          return (
            <span style={{ color: 'grey', cursor: 'pointer' }} onClick={() => this.editQa(row)}>
              {row.basicQuestion}
            </span>
          );
        },
      },
      {
        key: 'answer',
        align: 'left',
        title: formatMessage({ id: 'knowledgeManagement.qaList.answer' }),
        dataIndex: 'answer',
        render: (answer) => {
          return answer
            ? <div style={{ transform: 'translateY(-10px)' }}>
                <MarkdownRenderer
                  markdown={answer.replace(/<script/g, `<code>< script`).replace(/<\/script>/g, `</ script></code>`)}
                />
              </div>
            : '';
        },
      },
      /* {
        key: 'questionCount',
        // align: "center",
        title: formatMessage({ id: 'knowledgeManagement.qaList.similarQuestionCount' }),
        dataIndex: 'questionCount',
        width: 120,
      },
      {
        key: 'type',
        // align: "center",
        title: formatMessage({ id: 'knowledgeManagement.qaList.knowledgeType' }),
        dataIndex: 'type',
        width: 120,
      },
      {
        title: formatMessage({ id: 'knowledgeManagement.qaList.createTime' }),
        dataIndex: 'createTime',
        key: 'createTime',
        width: 150,
        render: (createTime) => {
          if (createTime) {
            return moment(createTime).format('YYYY-MM-DD HH:mm:ss');
          } else {
            return createTime;
          }
        },
      }, */
      {
        title: formatMessage({ id: 'knowledgeManagement.qaList.upadateTime' }),
        dataIndex: 'updateTime',
        key: 'updateTime',
        width: 150,
        render: (updateTime) => {
          if (updateTime) {
            return moment(updateTime).format('YYYY-MM-DD HH:mm:ss');
          } else {
            return updateTime;
          }
        },
      },
      {
        title: formatMessage({ id: 'knowledgeManagement.qaList.operation' }),
        width: 280,
        render: (text, row) => {
          return (
            <Button icon='eye' type='primary' size='small' style={{ marginRight: 5 }} onClick={() => this.editQa(row)}>
              {formatMessage({ id: 'knowledgeManagement.qaList.view' })}
            </Button>
          );
        },
      },
    ];
    this.uploadProps = {
      name: 'file',
      action: '/qa/importNew',
      accept: '.xlsx',
      onChange: this.handleChangeByUpload,
    };
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
    const { sortType } = this.props;
    this.setState({ sortType: sortType || 1 });
    this.getPublishingStatus();
  }

  getPublishingStatus = async (type) => {
    const res = await getBatchSyncCheck({ rootCategoryId: this.props.id });
    console.log(res);
    if (res.code === 0) {
      this.setState({ resynchronizationStatus: res.data });
      if (!res.data.isSync) {
        if (checkInterval) {
          clearTimeout(checkInterval);
          checkInterval = null;
        }
      } else {
        checkInterval = setTimeout(() => {
          this.getPublishingStatus();
        }, 5000);
      }
    } else {
      this.setState({ resynchronizationStatus: { isSync: false } });
      if (type && checkInterval) {
        clearTimeout(checkInterval);
        checkInterval = null;

        return notification.open({
          key: 'notificationKey',
          message: res.msg,
          icon: <Icon type='close-circle' style={{ color: 'red' }} />,
        });
      }
      if (checkInterval) {
        clearTimeout(checkInterval);
        checkInterval = null;
      }
    }
  };

  getListByTreeRoot(treeRoot) {
    this.setState(
      {
        categoryId: treeRoot.id,
        categoryParentId: treeRoot.parentId,
        categoryParentPath: treeRoot.Path,
        categoryName: treeRoot.title,
      },
      () => {
        this.fetchListBySearch();
      }
    );
  }

  getQaListByFortherCall(nodeId, nodeIdName, nodePath, isShared, parentPath, parentId) {
    const { currentUser, sortType, isNoAnswer } = this.props;
    console.log(nodeId, this.state.categoryId);
    if (nodeId !== this.state.categoryId) {
      this.setState(
        {
          categoryId: nodeId,
          nodePath,
          categoryName: nodeIdName,
          loading: true,
          page: 1,
          isShared,
          categoryParentId: parentId,
          categoryParentPath: parentPath,
        },
        () => {
          this.fetchListBySearch();
        }
      );
    }
  }

  getStr = (string, str, callback) => {
    const str_before = string.split(str)[0];
    const str_after = string.split(str)[1];
    callback(str_before, str_after);
  };

  // 搜索
  fetchListBySearch = (obj) => {
    const { dispatch, currentUser, noAnswer, id, urlParams } = this.props;

    let object = {};
    if (obj) {
      object = obj;
    }
    this.setState({ tableLoading: true }, async () => {
      object.disabled = this.props.form.getFieldValue('disabled');
      if (object.disabled === 'All') {
        delete object.disabled;
      } else {
        object.disabled = object.disabled === 'true' ? 1 : 0;
      }
      object.qaType = this.state.qaType;
      if (object.qaType === 'All') {
        delete object.qaType;
      }
      object.size = this.state.limit;
      object.current = this.state.page;
      object.search = this.state.key;
      object.categoryId = this.state.categoryId === '' ? `${currentUser.robotId}-root` : this.state.categoryId;
      object.categoryParentPath = this.state.categoryParentPath;
      object.searchType = object.queryType === undefined ? this.state.queryType : object.queryType;
      object.isNoneAnswer = this.state.isNoAnswer;
      object.orderType = this.state.sortType;
      object.urlPrefix = UserSession.isSystemKnowledge() ? 1 : null;
      if (UserSession.isSystemKnowledge()) {
        let res = await knowledgeListQa(object);
        this.setState({
          res: res.records,
          total: res.total,
          searchObj: object,
          loading: false,
          tableLoading: false,
          qaIdList: [],
          classId: '',
          selectedRowKeys: [],
        });
      } else {
        dispatch({
          type: 'qaList/fetchListBySearch',
          payload: object,
          callback: (res) => {
            this.setState({
              res: res.records,
              total: res.total,
              searchObj: object,
              loading: false,
              tableLoading: false,
              qaIdList: [],
              classId: '',
              selectedRowKeys: [],
            });
          },
        });
      }
    });
  };

  handleChange = (value) => {
    this.setState({ sortType: value, loading: true }, () => {
      this.fetchListBySearch();
    });
  };

  fetchQaListBySearch = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      const obj = values;
      if (!err) {
        this.setState({ key: obj.key, page: 1 }, () => {
          this.fetchListBySearch(obj);
        });
      }
    });
  };

  reference = () => {
    const { selectedRowKeys } = this.state;
    if (!(selectedRowKeys.length > 0)) {
      return message.error(formatMessage({ id: 'knowledgeManagement.qaList.validation.selectKnowledge' }));
    }
    if (this.referenceTemplateRef) {
      this.referenceTemplateRef.init({ type: null, id: [...selectedRowKeys] });
    }
  };

  stopQaByQaId = (row, type) => {
    const { dispatch, currentUser } = this.props;
    const { selectedRowKeys } = this.state;
    let arr = [];
    if (row) {
      arr.push(row.id);
    } else {
      arr = selectedRowKeys;
    }
    if (arr.length === 0) {
      return message.error(formatMessage({ id: 'knowledgeManagement.qaList.validation.selectOperationKnowledge' }));
    }
    this.setState({ enableLoading: !type }, () => {
      dispatch({
        type: 'qaList/stopQaByQaId',
        payload: { ids: arr, disabled: type },
        callback: (res) => {
          message.info(res.msg);
          this.setState({ loading: true, enableLoading: false }, () => {
            this.fetchListBySearch();
          });
        },
      });
    });
  };

  // 翻页
  fanye(e) {
    this.setState({ page: e, loading: true, tableLoading: true, selectedRowKeys: [] }, () => {
      this.fetchListBySearch();
    });
  }

  // 导入弹出层
  handleOk = (e) => {
    const { fileList } = this.state;
    const { id } = this.props;
    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('file', file.originFileObj);
      formData.append('rootCategoryId', id);
    });
    this.props.isShowGlobalLoading(true, 'btn');
    this.setState({ uploading: true, visible: false }, () => {
      this.uploadFile(formData);
    });
  };

  handleQa = (e) => {
    if (this.state.mergeId === '') {
      return message.error(formatMessage({ id: 'knowledgeManagement.qaList.validation.selectMergeQuestion' }));
    }
    this.combine();
  };

  handleQaCancel = (e) => {
    this.setState({ mergeVisible: false, qaKey: '' });
  };

  handleCancel = (e) => {
    this.setState({
      visible: false,
      mergeVisible: false,
      qaKey: '',
      fileList: [],
      uploading: false,
    });
  };

  handleClass = (e) => {
    this.updateQACategory();
  };

  updateQACategory = () => {
    if (!this.state.classId) {
      return message.error(formatMessage({ id: 'knowledgeManagement.qaList.validation.selectCategory' }));
    }
    const { dispatch } = this.props;
    this.setState({ moveLoading: true }, () => {
      const that = this;
      dispatch({
        type: 'qaList/moveQaCategory',
        payload: {
          qaIds: that.state.qaIdList,
          categoryId: that.state.classId,
          parentPath: that.state.movePath,
        },
        callback: (res) => {
          that.setState({ classVisible: false });
          message.info(res.message);
          that.fetchListBySearch();
          that.setState({ moveLoading: false });
        },
      });
    });
  };

  handleClassCancel = (e) => {
    this.setState({ classVisible: false, qaIdList: [], classId: null, movePath: '' });
  };

  handleClassShow = (e) => {
    if (this.state.selectedRowKeys.length === 0) {
      return message.error(formatMessage({ id: 'knowledgeManagement.qaList.validation.selectMoveCategoryKnowledge' }));
    }
    this.getCategoryListJson();
    this.setState({ classVisible: true, moveLoading: false });
  };

  showImportModal = () => {
    this.setState({ visible: true });
  };

  // 删除
  delQaByQaId(row) {
    const that = this;

    console.log(that.props);
    const { dispatch, currentUser } = that.props;
    let arr = [];
    if (row) {
      arr.push(row.id);
    } else {
      arr = that.state.qaIdList;
    }
    if (arr.length === 0) {
      return message.info(formatMessage({ id: 'knowledgeManagement.qaList.mergeModal.willDelete' }));
    }
    confirm({
      title: formatMessage({ id: 'knowledgeManagement.qaList.deleteModal.title' }),
      content: formatMessage({ id: 'knowledgeManagement.qaList.deleteModal.confirm' }),
      okText: formatMessage({ id: 'knowledgeManagement.qaList.confirm' }),
      cancelText: formatMessage({ id: 'knowledgeManagement.qaList.cancel' }),
      onOk: () => {
        dispatch({
          type: 'qaList/delListByQaId',
          payload: { ids: arr },
          callback: (resFetch) => {
            message.info(resFetch.msg);
            // 判断是否需要加载上一页数据 2022.4.8
            const { res, page } = that.state;
            const newCurrent = tableDataCheck(res, page, arr);
            that.setState({ qaIdList: [], page: newCurrent }, () => {
              that.fetchListBySearch();
            });
          },
        });
      },
      onCancel() {},
    });
  }

  editQa = (row) => {
    const { categoryId } = this.state;
    console.log(categoryId);
    this.EditingKnowledge.showEditDrawer(row, null, categoryId);
    // if (row) {
    //   this.props.editQaById(row._id, this.state.nodePath, row.isShared);
    // } else {
    //   this.props.editQaById('', this.state.nodePath, false);
    // }
  };

  // 添加
  showDrawer = () => {
    this.setState({ close: true });
  };

  onClose = () => {
    this.setState({ close: false });
  };

  // 合并知识点
  mergeQaByQaId = () => {
    if (this.state.qaIdList.length === 0) {
      return message.error(formatMessage({ id: 'knowledgeManagement.qaList.validation.selectMergeFirst' }));
    }
    this.fetchListByModalSerach();
    this.setState({ mergeVisible: true });
  };

  qaSearch = (val) => {
    this.setState({ qaKey: val, key: val, qaPage: 1 }, () => {
      this.fetchListByModalSerach();
    });
  };

  checkedQa = (e) => {
    this.setState({ mergeId: e.target.value._id });
  };

  fetchListByModalSerach = () => {
    const { dispatch, currentUser } = this.props;
    const object = {};
    object.robotId = currentUser.robotId;
    object.limit = this.state.qaLimit;
    object.page = this.state.qaPage;
    object.query = this.state.key;
    object.categoryId = '/';
    object.queryType = object.queryType === undefined ? this.state.queryType : object.queryType;
    object.isNoneAnswer = object.isNoneAnswer === undefined ? false : object.isNoneAnswer;
    object.sortType = this.state.sortType;
    dispatch({
      type: 'qaList/fetchListBySearch',
      payload: object,
      callback: (res) => {
        this.setState({ qaRes: res.list, qaTotal: res.total, qaLoading: false });
      },
    });
  };

  qaFanye = (e) => {
    this.setState({ qaPage: e }, () => {
      this.fetchListByModalSerach();
    });
  };

  combine = () => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'qaList/combine',
      payload: {
        robotId: currentUser.robotId,
        from: this.state.qaIdList,
        to: this.state.mergeId,
      },
      callback: (res) => {
        message.success(formatMessage({ id: 'knowledgeManagement.qaList.merge.success' }));
        this.setState({ mergeVisible: false, qaKey: '', key: '' }, () => {
          this.fetchListBySearch();
        });
      },
    });
  };

  onClassChange = (value, label, extra) => {
    console.log(extra);
    this.setState({
      classId: value,
      movePath: extra.triggerNode.props.info.parentPath,
    });
  };

  getCategoryListJson = () => {
    const { dispatch, id } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'qaList/categoryListJson',
        payload: { categoryId: id },
        callback: (res) => {
          const arr = [];
          arr.push(res[0]);
          this.setState({
            classTreeData: arr,
            classLoading: false,
            defaultExpandedKey: res[0].id,
          });
        },
      });
    });
  };

  renderTreeNodes(data) {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id} value={item.id} info={{ parentPath: item.parentPath }} disabled={item.parentPath === '/'}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.name} key={item.id} value={item.id} info={{ parentPath: item.parentPath }} disabled={item.parentPath === '/'} />;
    });
  }

  pageSizeChange = (current, size) => {
    this.setState({ page: current, limit: size, tableLoading: true }, () => {
      this.fetchListBySearch();
    });
  };

  setNoAnswer = (val) => {
    this.setState({ isNoAnswer: !val.target.value });
  };

  setQaKey = (e) => {
    this.setState({ qaKey: e.target.value, key: e.target.value });
  };

  setClassName = (record) => {
    return record.disabled ? styles.grey : '';
  };

  handleChangeByUpload = (info) => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map((file) => {
      if (file.response) {
        if (file.response.code) {
          message.error(file.response.msg);
        } else {
          file.url = file.response.url;
        }
      }
      return file;
    });
    this.setState({ fileList });
  };

  setQuery = (e) => {
    this.setState({ key: e.target.value });
  };

  setStatus = (e) => {
    this.setState({ disabled: e });
  };

  setQueryType = (e) => {
    this.setState({ queryType: e });
  };

  setQaType = (e) => {
    this.setState({ qaType: e });
  };

  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys, qaIdList: selectedRowKeys });
  };

  handleUpFile = (info) => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map((file) => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    this.setState({ fileList });
  };

  uploadFile = (data) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'qaList/knowledgeImport',
      payload: data,
      callback: (res) => {
        console.log(res);
        if (res.code === -1) {
          this.props.isShowGlobalLoading(false);
          this.setState({ uploading: false, visible: true, fileList: [] });
        } else {
          this.checkImport();
        }
      },
    });
  };

  downloadQaTemp = () => {
    window.open('/cloud/知识点导入模板.xlsx');
    // const { dispatch } = this.props;
    // dispatch({
    //   type: 'qaList/downladQA',
    //   payload: {},
    //   callback: res => {
    //     const fileName = decodeURIComponent(res.headers['content-disposition'].split('=')[1]);
    //     download.byBlob(res.fileBlob, filename);
    //   },
    // });
  };

  refreshList = () => {
    this.fetchListBySearch();
  };

  resetStatus = (flag) => {
    const { selectedRowKeys } = this.state;
    console.log(selectedRowKeys);
    if (selectedRowKeys.length == 0) {
      return message.warning(formatMessage({ id: 'knowledgeManagement.qaList.export.selectData' }));
    }
  };

  /**
   * 打开关联弹窗
   */
  checkRelated = () => {
    this.RelatedModal.openModal();
  };

  setIsNoneAnswer = (e) => {
    this.setState({ isNoAnswer: e.target.checked });
  };

  doExportQa = async () => {
    const { selectedRowKeys, res } = this.state;
    const { id } = this.props;

    if (res.length == 0) {
      message.warning(formatMessage({ id: 'knowledgeManagement.qaList.export.noData' }));
      return false;
    }
    if (selectedRowKeys.length > 0) {
      //导出选中的知识点
      const res = await exportByQaIds({ qaIdList: selectedRowKeys, rootCategoryId: id });
    } else {
      //导出全部
      const { qaType, limit, page, key, categoryId, categoryParentPath, queryType, isNoAnswer, sortType } = this.state;
      let object = {};
      object.disabled = this.props.form.getFieldValue('disabled');
      if (object.disabled === 'All') {
        delete object.disabled;
      } else {
        object.disabled = object.disabled === 'true' ? 1 : 0;
      }
      object.qaType = qaType;
      if (object.qaType === 'All') {
        delete object.qaType;
      }
      object.size = limit;
      object.current = page;
      object.search = key;
      object.categoryId = categoryId === '' ? `${currentUser.robotId}-root` : categoryId;
      object.categoryParentPath = categoryParentPath;
      object.searchType = object.queryType === undefined ? queryType : object.queryType;
      object.isNoneAnswer = isNoAnswer;
      object.orderType = sortType;
      object.urlPrefix = UserSession.isSystemKnowledge() ? 1 : null;
      object.rootCategoryId = id;
      const res = await exportQA(object);
    }
  };

  republish = () => {
    confirm({
      title: formatMessage({ id: 'knowledgeManagement.qaList.resyncModal.title' }),
      content: formatMessage({ id: 'knowledgeManagement.qaList.resyncModal.confirm' }),
      okText: formatMessage({ id: 'knowledgeManagement.qaList.resyncModal.ok' }),
      cancelText: formatMessage({ id: 'knowledgeManagement.qaList.resyncModal.cancel' }),
      onOk: async () => {
        const res = await postBatchSync({ rootCategoryId: this.props.id });
        console.log(res);
        if (res.code === 0) {
          this.getPublishingStatus(true);
        }
      },
      onCancel() {},
    });
  };

  checkImport = async () => {
    const res = await importQACheck({ rootCategoryId: this.props.id });
    switch (res.data) {
      case 0:
        //没有导入的任务
        this.props.isShowGlobalLoading(false);
        this.props.setCancelling(false);
        clearInterval(checkListInterval);
        checkListInterval = null;
        this.setState({ uploading: false, visible: false, fileList: [] }, () => {
          this.fetchListBySearch();
          this.props.treeList();
        });
        break;
      case 1:
        //导入中
        if (!checkListInterval) {
          checkListInterval = setInterval(() => {
            this.checkImport();
          }, 5000);
        }
        this.props.setCancelling(false);
        break;
      case 2:
        //导入失败
        this.props.isShowGlobalLoading(false);
        this.props.setCancelling(false);
        clearInterval(checkListInterval);
        checkListInterval = null;
        this.setState({ uploading: false, visible: false, fileList: [] }, () => {
          message.error(res.message);
          this.fetchListBySearch();
          this.props.treeList();
        });
        break;
      case 3:
        //导入成功
        this.props.isShowGlobalLoading(false);
        this.props.setCancelling(false);
        clearInterval(checkListInterval);
        checkListInterval = null;
        this.setState({ uploading: false, visible: false, fileList: [] }, () => {
          message.info(res.message);
          this.fetchListBySearch();
          this.props.treeList();
        });
        break;
      case 4:
        //取消导入中
        if (!checkListInterval) {
          checkListInterval = setInterval(() => {
            this.checkImport();
          }, 5000);
        }
        this.props.setCancelling(true);
        break;
    }
  };

  componentWillUnmount() {
    clearInterval(checkListInterval);
    checkListInterval = null;
  }

  setCheckListInterval = (data) => {
    checkListInterval = data;
  };

  moreMenuClick = (e) => {
    switch (e.key) {
      case 'add':
        this.editQa();
        break;
      case 'import':
        this.showImportModal();
        break;
      case 'start':
        this.stopQaByQaId(null, false);
        break;
      case 'stop':
        this.stopQaByQaId(null, true);
        break;
      case 'export':
        this.doExportQa();
        break;
      case 'sync':
        this.republish();
        break;
      case 'move':
        this.handleClassShow();
        break;
      case 'delete':
        this.delQaByQaId();
        break;
    }
  };

  changeTable = (pagination, filters, sorter, extra) => {
    console.log(pagination, filters, sorter, extra);
    if (sorter) {
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { items, total } = this.props.qaList;
    const {
      sortType,
      selectedRowKeys,
      uploading,
      fileList,
      categoryParentId,
      categoryParentPath,
      defaultExpandedKey,
      exportLoading,
      exportTipList,
      moveLoading,
      enableLoading,
      resynchronizationStatus,
      addMenuList,
      batchMenuList,
    } = this.state;
    const { isShared, authority, id } = this.props;
    const props = {
      onRemove: (file) => {
        this.setState((state) => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState((state) => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      accept: '.xlsx,.xls',
      fileList,
      onChange: this.handleUpFile,
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 20 },
      },
    };
    const tableSortIcon = {
      width: 20,
      verticalAlign: 'sub',
      cursor: 'pointer',
    };
    const columns = [
      {
        key: 'basicQuestion',
        align: 'left',
        title: formatMessage({ id: 'knowledgeManagement.qaList.standardQuestion' }),
        dataIndex: 'basicQuestion',
        width: 200,
        render: (text, row) => {
          return (
            <span style={{ color: 'grey', cursor: 'pointer' }} onClick={() => this.editQa(row)}>
              {row.basicQuestion}
            </span>
          );
        },
      },
      {
        key: 'answer',
        align: 'left',
        title: formatMessage({ id: 'knowledgeManagement.qaList.answer' }),
        dataIndex: 'answer',
        render: (answer) => {
          return answer
            ? <div style={{ transform: 'translateY(-10px)' }}>
                <MarkdownRenderer
                  markdown={answer.replace(/<script/g, `<code>< script`).replace(/<\/script>/g, `</ script></code>`)}
                />
              </div>
            : '';
        },
      },
      /* {
        key: 'questionCount',
        // align: "center",
        title: (
          <span>
            {formatMessage({ id: 'knowledgeManagement.qaList.similarQuestionCount' })}
            {sortType == 3 ? (
              <img src='../../../newUI/sortCheck.png' style={tableSortIcon} />
            ) : (
              <img src='../../../newUI/sort.png' style={tableSortIcon} onClick={() => this.handleChange(3)} />
            )}
          </span>
        ),
        dataIndex: 'questionCount',
        width: 120,
      },
      {
        key: 'type',
        // align: "center",
        title: formatMessage({ id: 'knowledgeManagement.qaList.knowledgeType' }),
        dataIndex: 'type',
        width: 120,
      },
      {
        title: (
          <span>
            {formatMessage({ id: 'knowledgeManagement.qaList.createTime' })}
            {sortType == 2 ? (
              <img src='../../../newUI/sortCheck.png' style={tableSortIcon} />
            ) : (
              <img src='../../../newUI/sort.png' style={tableSortIcon} onClick={() => this.handleChange(2)} />
            )}
          </span>
        ),
        dataIndex: 'createTime',
        key: 'createTime',
        width: 150,
        render: (createTime) => {
          if (createTime) {
            return moment(createTime).format('YYYY-MM-DD hh:mm:ss');
          } else {
            return createTime;
          }
        },
      }, */
      {
        title: (
          <span>
            {formatMessage({ id: 'knowledgeManagement.qaList.updateTime' })}
            {sortType == 1
                ? <img src='../../../newUI/sortDesc.png' style={tableSortIcon} onClick={() => this.handleChange(2)}  />
                : sortType == 2
                    ? <img src='../../../newUI/sortAsc.png' style={tableSortIcon} onClick={() => this.handleChange(0)} />
                    : <img src='../../../newUI/sort.png' style={tableSortIcon} onClick={() => this.handleChange(1)} />
            }
          </span>
        ),
        dataIndex: 'updateTime',
        key: 'updateTime',
        width: 150,
        render: (updateTime) => {
          if (updateTime) {
            return moment(updateTime).format('YYYY-MM-DD hh:mm:ss');
          } else {
            return updateTime;
          }
        },
      },
      {
        title: formatMessage({ id: 'knowledgeManagement.qaList.operation' }),
        width: 280,
        render: (text, row) => {
          return (
            <div>
              {!row.isShard ? (
                <>
                  <Button icon='edit' type='primary' size='small' style={{ marginRight: 5 }} onClick={() => this.editQa(row)}>
                    {this.props.authority === 1 ? (
                      formatMessage({ id: 'knowledgeManagement.qaList.view' })
                    ) : (
                      <FormattedMessage id='app.processTemplate.btn-edit' />
                    )}
                  </Button>
                  {UserSession.isAdmin() ? null : row.disabled ? (
                    <Button
                      icon='caret-right'
                      size='small'
                      style={{
                        marginRight: 5,
                        backgroundColor: '#14C6A1',
                        color: '#fff',
                      }}
                      onClick={() => this.stopQaByQaId(row, false)}
                      disabled={this.props.authority === 1}
                    >
                      <FormattedMessage id='app.overView.start' />
                    </Button>
                  ) : (
                    <Button
                      icon='stop'
                      size='small'
                      style={{
                        marginRight: 5,
                        backgroundColor: 'orange',
                        color: '#fff',
                      }}
                      onClick={() => this.stopQaByQaId(row, true)}
                      disabled={this.props.authority === 1}
                    >
                      <FormattedMessage id='app.overView.stop' />
                    </Button>
                  )}
                  {this.props.authority === 1 || UserSession.whetherCanDelete() ? (
                    ''
                  ) : (
                    <Button
                      type='danger'
                      icon='delete'
                      size='small'
                      style={{
                        marginRight: 5,
                        backgroundColor: 'red',
                        color: '#fff',
                      }}
                      onClick={() => this.delQaByQaId(row)}
                      disabled={this.props.authority === 1 || UserSession.whetherCanDelete()}
                    >
                      <FormattedMessage id='app.processTemplate.btn-del' />
                    </Button>
                  )}
                </>
              ) : (
                <div>
                  <Button
                    icon='edit'
                    type='primary'
                    size='small'
                    style={{ marginRight: 5 }}
                    onClick={() => this.editQa(row)}
                    disabled={this.props.authority === 1}
                  >
                    <FormattedMessage id='app.processTemplate.btn-edit' />
                  </Button>
                </div>
              )}
            </div>
          );
        },
      },
    ];

    return (
      <Suspense fallback={<PageLoading />}>
        <div className={styles.qaListClass} style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 24 }}>
          <Form layout='inline' onSubmit={this.fetchQaListBySearch}>
            <Form.Item>
              {getFieldDecorator('key')(
                <Input
                  placeholder={formatMessage({ id: 'knowledgeManagement.qaList.searchPlaceholder' })}
                  style={{ width: 240 }}
                  allowClear
                  onChange={this.setQuery}
                />
              )}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator('queryType', { initialValue: 1 })(
                <Select style={{ width: 160 }} onChange={this.setQueryType} suffixIcon={<Icon type='caret-down' />}>
                  <Option value={1}>{formatMessage({ id: 'knowledgeManagement.qaList.queryType.question' })}</Option>
                  <Option value={2}>{formatMessage({ id: 'knowledgeManagement.qaList.queryType.answer' })}</Option>
                  {/* <Option value={3}>{formatMessage({ id: 'knowledgeManagement.qaList.queryType.slot' })}</Option>
									<Option value={4}>{formatMessage({ id: 'knowledgeManagement.qaList.queryType.api' })}</Option> */}
                </Select>
              )}
            </Form.Item>
            {UserSession.isAdmin() || UserSession.isSystemKnowledge() ? null : (
              <Form.Item>
                {getFieldDecorator('disabled', { initialValue: 'All' })(
                  <Select style={{ width: 160 }} onChange={this.setStatus} suffixIcon={<Icon type='caret-down' />}>
                    <Option value='All'>{formatMessage({ id: 'knowledgeManagement.qaList.status.all' })}</Option>
                    <Option value='false'>{formatMessage({ id: 'knowledgeManagement.qaList.status.enabled' })}</Option>
                    <Option value='true'>{formatMessage({ id: 'knowledgeManagement.qaList.status.disabled' })}</Option>
                  </Select>
                )}
              </Form.Item>
            )}
            {/* <Form.Item>
							{getFieldDecorator("qaType", { initialValue: "All" })(
								<Select style={{ width: 160 }} onChange={this.setQaType} suffixIcon={<Icon type="caret-down" />}>
									<Option value={1}>{formatMessage({ id: 'knowledgeManagement.qaList.type.normal' })}</Option>
									<Option value={2}>{formatMessage({ id: 'knowledgeManagement.qaList.type.slot' })}</Option>
									<Option value='All'>{formatMessage({ id: 'knowledgeManagement.qaList.type.all' })}</Option>
								</Select>
							)}
						</Form.Item> */}
            {UserSession.isAdmin() || UserSession.isSystemKnowledge() ? null : (
              <Form.Item style={{ height: '52px', display: 'inline-flex', alignItems: 'center' }}>
                {getFieldDecorator('isNoneAnswer', {
                  valuePropName: 'checked',
                  initialValue: false,
                })(<Checkbox onChange={this.setIsNoneAnswer}>{formatMessage({ id: 'knowledgeManagement.qaList.filter.noAnswer' })}</Checkbox>)}
              </Form.Item>
            )}
            <Form.Item>
              <Button type='primary' htmlType='submit'>
                {formatMessage({ id: 'knowledgeManagement.qaList.search' })}
              </Button>
            </Form.Item>
          </Form>
          {UserSession.isSystemKnowledge() ? (
            <Button icon='block' onClick={this.reference}>
              {formatMessage({ id: 'knowledgeManagement.qaList.reference' })}
            </Button>
          ) : null}
          {!isShared ? (
            <div style={{ flexShrink: '0' }}>
              <MoreOption
                menuList={addMenuList}
                btnInfo={{ name: formatMessage({ id: 'knowledgeManagement.qaList.add' }), style: { marginRight: 8 } }}
                moreMenuClick={this.moreMenuClick}
              />
              <MoreOption
                menuList={batchMenuList}
                btnInfo={{ name: formatMessage({ id: 'knowledgeManagement.qaList.operation' }), style: { marginRight: 8 } }}
                moreMenuClick={this.moreMenuClick}
              />
              {
                // {UserSession.whetherCanDelete() ? null : (
                //   <Button type='primary' style={{ margin: '5px 5px 5px 0' }} onClick={() => this.editQa()} disabled={authority === 1}>新增</Button>
                // )}
                // {UserSession.isSystemKnowledge() || UserSession.isAdmin() ? null : (
                //   <Button style={{ margin: 5 }} onClick={() => this.stopQaByQaId(null, false)} disabled={authority === 1} loading={enableLoading}>
                //     {UserSession.isAdmin() ? '发布' : '启用'}
                //   </Button>
                // )}
                // {UserSession.isSystemKnowledge() || UserSession.isAdmin() ? null : (
                //   <Button style={{ margin: 5 }} onClick={() => this.stopQaByQaId(null, true)} disabled={authority === 1}>
                //     {UserSession.isAdmin() ? '取消发布' : '停用'}
                //   </Button>
                // )}
                // {UserSession.whetherCanDelete() ? null : (
                //   <Button onClick={this.showImportModal} style={{ margin: 5 }}>导入</Button>
                // )}
                // {UserSession.whetherCanDelete() ? null : (
                //   <Button onClick={this.doExportQa} style={{ margin: 5 }}>导出</Button>
                // )}
                // {UserSession.whetherCanDelete() ? null : (
                //   <Button onClick={() => this.handleClassShow()} style={{ margin: 5 }}>
                //     <FormattedMessage id='app.overView.remove' />
                //   </Button>
                // )}
                // {UserSession.whetherCanDelete() ? null : (
                //   <Button onClick={() => this.delQaByQaId()} style={{ margin: 5 }} disabled={authority === 1}>
                //     <FormattedMessage id='app.overView.del' />
                //   </Button>
                // )}
                // {UserSession.whetherCanDelete() ? null : (
                //   <Button onClick={this.republish} loading={resynchronizationStatus ? resynchronizationStatus.isSync : true} style={{ margin: 5 }}>重新同步</Button>
                // )}
              }
            </div>
          ) : null}
        </div>
        <Table
          rowSelection={rowSelection}
          rowClassName={this.setClassName}
          columns={UserSession.isSystemKnowledge() ? this.sysColumns : columns}
          dataSource={this.state.res}
          rowKey='id'
          pagination={false}
          loading={this.state.tableLoading}
          scroll={{ x: 'auto', y: 530 }}
          onChange={this.changeTable}
        />
        {parseInt(this.state.total) > 10 ? (
          <Pagination
            // showSizeChanger
            showQuickJumper
            total={parseInt(this.state.total)}
            current={this.state.page}
            onChange={(e) => this.fanye(e)}
            style={{ textAlign: 'right', marginTop: 16 }}
            // onShowSizeChange={(current, size) => this.pageSizeChange(current, size)}
          />
        ) : null}
        <Modal
          title={<FormattedMessage id='app.overView.leadQa' />}
          visible={this.state.visible}
          onCancel={this.handleCancel}
          width='630px'
          centered
          footer={[
            <Button key='back' onClick={this.handleCancel}>
              {formatMessage({ id: 'app.overView.cancel' })}
            </Button>,
            <Button key='submit' type='primary' loading={uploading} disabled={fileList.length === 0} onClick={this.handleOk}>
              {uploading
                ? formatMessage({ id: 'knowledgeManagement.qaList.importModal.importing' })
                : formatMessage({ id: 'knowledgeManagement.qaList.importModal.startImport' })}
            </Button>,
          ]}
        >
          <Form {...formItemLayout}>
            <Form.Item label={<FormattedMessage id='app.overView.file' />}>
              <Upload {...props}>
                <Button>
                  <Icon type='upload' /> <FormattedMessage id='app.overView.file' />
                </Button>
              </Upload>
            </Form.Item>
            <Form.Item label={<FormattedMessage id='app.overView.file' />}>
              <div style={{ border: '1px solid grey', padding: 10, borderRadius: 10, overflow: 'hidden' }}>
                <div>
                  {formatMessage({ id: 'knowledgeManagement.qaList.mergeModal.qaTemp1' })}
                  <span style={{ color: 'blue', cursor: 'pointer' }} onClick={() => this.downloadQaTemp()}>
                    {formatMessage({ id: 'knowledgeManagement.qaList.mergeModal.downloadQaTemp' })}
                  </span>
                  {/* <a href="/knowledge/base/import/template" download="知识点导入模板">下载知识点导入模板</a> */}
                </div>
                <div>{formatMessage({ id: 'knowledgeManagement.qaList.mergeModal.qaTemp2' })}</div>
                <div>{formatMessage({ id: 'knowledgeManagement.qaList.mergeModal.qaTemp3' })}</div>
              </div>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          title={formatMessage({ id: 'knowledgeManagement.qaList.mergeModal.title' })}
          visible={this.state.mergeVisible}
          onOk={this.handleQa}
          onCancel={this.handleQaCancel}
          okText={formatMessage({ id: 'knowledgeManagement.qaList.mergeModal.merge' })}
          cancelText={formatMessage({ id: 'knowledgeManagement.qaList.mergeModal.cancel' })}
          width='464px'
          centered
        >
          <Spin tip='Loading...' spinning={this.state.qaLoading}>
            <div style={{ overflow: 'hidden' }}>
              <p>{formatMessage({ id: 'knowledgeManagement.qaList.validation.selectMergeFirst' })}</p>
              <div style={{ padding: 10 }}>
                <div>
                  <Search
                    placeholder={formatMessage({ id: 'knowledgeManagement.qaList.mergeModal.searchPlaceholder' })}
                    onSearch={(value) => this.qaSearch(value)}
                    value={this.state.qaKey}
                    onChange={(e) => this.setQaKey(e)}
                    style={{ width: 300 }}
                  />
                </div>
                <div>
                  <RadioGroup onChange={this.checkedQa}>
                    {this.state.qaRes.map((qa, index) => {
                      return (
                        <div key={index} style={{ marginTop: 10 }}>
                          <Radio value={qa}>
                            <span style={{ marginLeft: 10, display: 'inline-block', maxWidth: 318, whiteSpace: 'initial' }}>{qa.stdQuestion}</span>
                          </Radio>
                        </div>
                      );
                    })}
                  </RadioGroup>
                </div>
              </div>
              <p style={{ color: 'grey', fontSize: 12, marginTop: 10 }}>
                {formatMessage({ id: 'knowledgeManagement.qaList.mergeModal.description' })}
              </p>
              <Pagination
                size='small'
                total={parseInt(total)}
                pageSize={6}
                onChange={(e) => this.qaFanye(e)}
                style={{ float: 'right', marginTop: '10px' }}
              />
            </div>
          </Spin>
        </Modal>
        <Modal
          title={formatMessage({ id: 'knowledgeManagement.qaList.moveModal.title' })}
          visible={this.state.classVisible}
          onOk={this.handleClass}
          onCancel={this.handleClassCancel}
          okText={formatMessage({ id: 'knowledgeManagement.qaList.confirm' })}
          cancelText={formatMessage({ id: 'knowledgeManagement.qaList.cancel' })}
          width='464px'
          centered
          confirmLoading={moveLoading}
        >
          <Spin tip='Loading...' spinning={this.state.classLoading}>
            <div style={{ overflow: 'hidden' }}>
              <Form {...formItemLayout}>
                <Form.Item label={formatMessage({ id: 'knowledgeFile.fileList.label.moveToCategory' })}>
                  <TreeSelect
                    style={{ width: 300, marginLeft: 10 }}
                    allowClear
                    showSearch
                    placeholder={formatMessage({ id: 'knowledgeManagement.qaList.validation.selectCategory' })}
                    treeNodeFilterProp='title'
                    value={this.state.classId}
                    treeDefaultExpandedKeys={[defaultExpandedKey]}
                    showCheckedStrategy='SHOW_PARENT'
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    onChange={(value, label, extra) => this.onClassChange(value, label, extra)}
                  >
                    {this.renderTreeNodes(this.state.classTreeData)}
                  </TreeSelect>
                </Form.Item>
              </Form>
            </div>
          </Spin>
        </Modal>
        <EditingKnowledge
          onRef={(ref) => (this.EditingKnowledge = ref)}
          refreshList={this.refreshList}
          categoryId={this.state.categoryId}
          authority={authority}
          pathId={id}
          urlPrefix={UserSession.isSystemKnowledge() ? 1 : null}
        />
        <RelatedModal onRef={(ref) => (this.RelatedModal = ref)} />
        <ReferenceTemplate onRef={(ref) => (this.referenceTemplateRef = ref)} setId={() => this.setState({ selectedRowKeys: [] })} />
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(QaList));
